import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {ParamConfig} from '../common/param.config';
import 'rxjs/add/operator/toPromise';
import {LogicInfo, LogicInfoPage} from './logicAdmin';
import {UserService} from '../user/user.service';
import {Router} from '@angular/router';

@Injectable()
export class LogicAdminService {
  public token: string;
  private hostUrl = ParamConfig.HTTP_WEB_HOST_URL + 'logicNode/getLogicNodeData'; // URL to web api
  private hostUrlGetMap = ParamConfig.HTTP_WEB_HOST_URL + 'rbMap/getMapByRobotId'; // 获取地图
  private hostUrlDeleteLogic = ParamConfig.HTTP_WEB_HOST_URL + 'logicNode/deleteLogicNode'; // URL to web api
  private hostUrlGetPath = ParamConfig.HTTP_WEB_HOST_URL + 'path/getPathData'; // URL to web api
  nodeId: string;

  constructor(private http: Http, private userService: UserService, private router: Router) {
  }

// 查询逻辑
  getLogic(page, mapId, pathId): Promise<any> {
    this.token = this.userService.getToken();
    const request = JSON.stringify({
      rows: ParamConfig.DATA_LIST_PAGE_SIZE,
      page: page,
      mapId: mapId,
      pathId: pathId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrl, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            const pagedata = new LogicInfoPage();
            pagedata.logicInfo = body as LogicInfo[];
            pagedata.totalPages = body.total;
            return pagedata;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

// 删除路径
  removeLogicInfo(logicInfo: LogicInfo): Promise<any> {
    const request = JSON.stringify({
      nodeId: logicInfo.nodeId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlDeleteLogic, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 获取编号
  getNodeId(logicInfo: LogicInfo) {
    this.nodeId = logicInfo.nodeId;
  }

  sendNodeId() {
    return this.nodeId;
  }

  // 获取mapid
  getMap(): Promise<any> {
    this.token = this.userService.getToken();
    const request = JSON.stringify({
      robotId: ''
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlGetMap, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return [true, body];
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

// 查询路径
  getPath(page, mapId): Promise<any> {
    this.token = this.userService.getToken();
    const request = JSON.stringify({
      rows: ParamConfig.DATA_LIST_PAGE_SIZE,
      page: page,
      mapId: mapId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlGetPath, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return [true, body];
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<[boolean, any]> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject([false, error.toString()]);
  }
}
